import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse, HttpEvent, HttpResponseBase } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { mergeMap, catchError } from 'rxjs/operators';
import { _HttpClient } from '@delon/theme';
import { environment } from '@env/environment';
import { LocalStorage } from '@core/local.storage';
import { ClearLoginService } from '@core/clearLogin.service';

@Injectable({ providedIn: 'root' })

export class DefaultInterceptor implements HttpInterceptor {
    constructor(
        private injector: Injector,
        public ls: LocalStorage,
        private router: Router,
        private clearLoginService: ClearLoginService
    ) { }

    private handleData(ev: HttpResponseBase): Observable<any> {
        // 可能会因为 `throw` 导出无法执行 `_HttpClient` 的 `end()` 操作
        if (ev.status > 0) {
            this.injector.get(_HttpClient).end();
        }
        if (ev.url && ev.url.indexOf('/csmis/login/login.jwt') !== -1 && ev.status === 200) {
            this.ls.set('authorization', ev.headers.get('authorization'));
        }
        switch (ev.status) {
            case 200:
                const response: any = ev;
                if (response.body && response.body.type === 'login_fail') {
                    this.clearLoginService.clearAll();
                    this.router.navigate(['passport/login']);
                }
                break;
            // case 403:
            // case 504:
            //     this.clearLoginService.clearAll();
            //     this.router.navigate(['exception/404']);
            //     break;
        }
        return of(ev);
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let newReq: any = '';
        let requrl: any = req.url;
        const auth: any = this.ls.get('authorization');

        if (!requrl.startsWith('https://') && !requrl.startsWith('http://')) {
            requrl = environment.SERVER_URL + requrl;
        }
        newReq = auth ? req.clone({ url: requrl, headers: req.headers.set('authorization', this.ls.get('authorization')), withCredentials: true }) : req.clone({ url: requrl, withCredentials: true });

        return next.handle(newReq).pipe(
            mergeMap((event: any) => {
                // 允许统一对请求错误处理
                if (event instanceof HttpResponseBase) {
                    return this.handleData(event);
                }
                // 若一切都正常，则后续操作
                return of(event);
            }),
            catchError((err: HttpErrorResponse) => this.handleData(err))
        );
    }
}
